package com.demon.framework.boot.xss;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import java.util.HashMap;
import java.util.Map;

/**
 * Filter配置
 *
 * @author Demon-HY
 * @date 2020-7-23
 */
@Configuration
@ConditionalOnProperty(value = "xss.enabled")
public class XssFilterConfig {

    /**
     * 过滤开关,默认关闭
     */
    @Value("${xss.enabled}")
    private String enabled;

    /**
     * 用于配置不需要参数过滤的请求url（多个用逗号分隔）
     */
    @Value("${xss.excludes:/favicon.ico,/img/*,/js/*,/css/*}")
    private String excludes;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    public FilterRegistrationBean xssFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns("/*");
        registration.setName("xssFilter");
        registration.setOrder(Integer.MAX_VALUE);
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("excludes", excludes);
        initParameters.put("enabled", enabled);
        registration.setInitParameters(initParameters);
        return registration;
    }
}
